package io.vov.vitamio.tvpaser;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串处理工具类
 * 
 * @author Administrator
 * 
 */
public class StringUtil {
	
	// 每个月的第一天，生成格式如下 2010-09-01
	public static final String MONTH_FIRSTDAY = "01";
	public static final String STRING_ZERO = "0";

	public static final String HOURS_START = " 00:00:00";
	public static final String HOURS_END = " 23:59:59";
	public static final String EMPTY_STRING = "";
	public static final String STRING_SPACE = " ";
	public static final String STRING_SPLIT = "-";
	public static final String STRING_CHARACTER = "/";
	public static final String SPLITTER_COMMA = ",";
	
	/**
	 * 以http作为协议开头
	 */
	public static final String PROTOCOL_TYPE_HTTP = "http://" ;
	/**
	 * 以https作为协议开头
	 */
	public static final String PROTOCOL_TYPE_HTTPS = "https://" ;
	
	public static Integer toInteger(Object srcStr, Integer defaultValue) {
		try {
			if (srcStr != null && StringUtil.isInt(srcStr)) {
				String s = srcStr.toString().replaceAll("(\\s)", "");
				return s.length() > 0 ? Integer.valueOf(s) : defaultValue;
			}
		} catch (Exception e) {

		}
		return defaultValue;
	}

	public static Integer parseCategoryId(Object srcStr, Integer defaultValue) {
		try {
			char[] chars = srcStr.toString().toCharArray();
			StringBuilder result = new StringBuilder();
			for (char c : chars) {
				if (c >= '0' && c <= '9') {
					result.append(c);
				}
			}
			return toInteger(result.toString(), defaultValue);
		} catch (Exception e) {

		}
		return defaultValue;
	}

	public static boolean isInt(Object srcStr) {
		if (srcStr == null) {
			return false;
		}
		String s = srcStr.toString().replaceAll("(\\s)", "");
		Pattern p = Pattern.compile("([-]?[\\d]+)");
		Matcher m = p.matcher(s);
		return m.matches();
	}

	public static boolean isEmpty(Object srcStr) {
		return nvl(srcStr, "").trim().length() == 0 || nvl(srcStr, "").equals("null");
	}

	public static String nvl(Object src, String alt) {
		if (src == null) {
			return alt;
		} else {
			return nvl(src.toString(), alt);
		}
	}

	public static String nvl(String srcStr, String objStr) {
		if (srcStr == null || 0 == srcStr.trim().length() || "null".equalsIgnoreCase(srcStr.trim())) {
			return objStr;
		} else {
			return srcStr;
		}
	}

	public static boolean isIn(String str, String[] strs) {
		if ((null == str) || (str.trim().equals("")) || (null == strs)) {
			return false;
		}

		boolean flag = false;

		for (int i = 0; i < strs.length; i++) {
			if (strs[i] != null && str.trim().equalsIgnoreCase(strs[i].trim())) {
				flag = true;

				break;
			}
		}

		return flag;
	}

	public static String formatDate(Date date) {
		if (date == null) {
			return null;
		}

		SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DEFAULT_DATE_PARSE);
		return dateFormat.format(date);
	}

	public static String formatDate(Date date, String format) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

	public static Date[] getCurrentMonth(Date currDate) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(currDate);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		Date fromDate = cal.getTime();

		cal.add(Calendar.MONTH, 1);
		cal.add(Calendar.DAY_OF_MONTH, -1);
		Date toDate = cal.getTime();
		return new Date[] { fromDate, toDate };
	}

	public static String[] getCurrentDay(String currDate) {
		return new String[] { currDate + HOURS_START, currDate + HOURS_END };
	}

	/**
	 * currDate格式为 2010-09-28,daysOfMonth为该月的总天数 ; 返回的String格式为 2010-09-01
	 * 00:00:00 和 2010-09-30 00:59:59
	 * 
	 * @param currDate
	 * @param daysOfMonth
	 * @return
	 */
	public static String[] getCurrentMonth(String currDate, int daysOfMonth) {

		String yearAndMonth = currDate.substring(0, currDate.lastIndexOf(STRING_SPLIT) + 1);

		return new String[] { yearAndMonth + MONTH_FIRSTDAY + HOURS_START, yearAndMonth + daysOfMonth + HOURS_END };
	}

	public static String trim(Object srcStr) {
		if (srcStr != null) {
			return srcStr.toString().trim();
		}

		return null;
	}

	public static String replaceString(String originalStr, String beReplaceSubStr, String replaceSubStr) {
		StringBuffer tmpStr = new StringBuffer();

		int spos = 0;

		int epos = 0;

		if (originalStr == null) {
			return "";
		} else if ((beReplaceSubStr == null) || (replaceSubStr == null)) {
			return originalStr;
		}

		while ((epos = originalStr.indexOf(beReplaceSubStr, spos)) != -1) {
			tmpStr.append(originalStr.substring(spos, epos));

			tmpStr.append(replaceSubStr);

			spos = epos + beReplaceSubStr.length();
		}

		if (spos < originalStr.length()) {
			tmpStr.append(originalStr.substring(spos));
		}

		return new String(tmpStr);
	}

	public static boolean isLatestCode(String currCode, String dbVersionCode) {
		int currCodeInt = Integer.parseInt(currCode.substring(currCode.length() - 6, currCode.length()), 0);
		int dbVersionCodeInt = Integer.parseInt(dbVersionCode.substring(dbVersionCode.length() - 6, dbVersionCode.length()), 0);
		if (currCodeInt > dbVersionCodeInt) {
			return true;
		}
		return false;
	}

	/**
	 * 判断byte数组是否为空或空长度
	 * 
	 * @param array
	 * @return
	 */
	public static boolean isNull(byte[] array) {
		return (null == array || array.length == 0);
	}

	/**
	 * 判断集合是否为空或空长度
	 * 
	 * @param col
	 * @return
	 */
	public static boolean isNull(Collection col) {
		return (null == col || col.isEmpty());
	}

	/**
	 * 判断Object 数组是否为空或空长度
	 * 
	 * @param array
	 * @return
	 */
	public static boolean isNull(Object[] array) {
		return (null == array || array.length == 0);
	}

	/**
	 * 判断字符串是否为空或空长度
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isNull(String value) {
		return (null == value || value.trim().length() == 0 || "null".equals(value));
	}

	public static String trimLeft(String srcStr) {
		if (srcStr != null && srcStr.length() > 0) {
			int i = 0;
			for (; i < srcStr.length(); i++) {
				char c = srcStr.charAt(i);
				if (c != ' ' && c != '\r' && c != '\t') {
					break;
				}
			}
			if (i > 0) {
				return srcStr.substring(i);
			} else {
				return srcStr;
			}
		}

		return srcStr;
	}

	public static String trimLeftExceptLine(String srcStr) {
		if (srcStr != null && srcStr.length() > 0) {
			StringBuilder stringBuilder = new StringBuilder();
			int i = 0;
			for (; i < srcStr.length(); i++) {
				char c = srcStr.charAt(i);
				int m = (int) c;
				// System.out.println("m value is " + m);
				if (c == ' ' || c == '\r' || c == '\t') {
					continue;
					// break;
				} else if (c == '\n' || m == 12288) {
					stringBuilder.append(c);
				} else if (m == 57529 || m == 57537 || m == 57531 || m == 57532 || m == 9633 || m == 38472 || m == 57534) { // 出现的一个乱码，可能是中文空格或换行
					continue;
				} else {
					break;
				}
			}
			if (i > 0) {
				return stringBuilder.append(srcStr.substring(i)).toString();
			} else {
				return srcStr;
			}
		}

		return srcStr;
	}

	/**
	 * 
	 * @param str
	 * @param trimChar
	 * @return
	 * @author shenzhongshan
	 */
	public static String trimLeft(String str, char trimChar) {
		if (str == null) {
			return null;
		}
		if (trimChar == ' ') {
			return str.trim();
		}
		int len = str.length();
		int st = 0;
		int off = 0; /* avoid getfield opcode */
		char[] val = str.toCharArray(); /* avoid getfield opcode */

		while ((st < len) && (val[off + st] == trimChar)) {
			st++;
		}

		return ((st > 0) || (len < str.length())) ? str.substring(st, len) : str;
	}

	/**
	 * 
	 * @param str
	 * @param trimChar
	 * @return
	 * @author shenzhongshan
	 */
	public static String trimRight(String str, char trimChar) {
		if (str == null) {
			return null;
		}
		if (trimChar == ' ') {
			return str.trim();
		}
		int len = str.length();
		int st = 0;
		int off = 0; /* avoid getfield opcode */
		char[] val = str.toCharArray(); /* avoid getfield opcode */

		while ((st < len) && (val[off + len - 1] == trimChar)) {
			len--;
		}
		return ((st > 0) || (len < str.length())) ? str.substring(st, len) : str;
	}

	/**
	 * 
	 * @param str
	 * @param trimChar
	 * @return
	 * @author shenzhongshan
	 */
	public static String trim(String str, char trimChar) {
		return trimRight(trimLeft(str, trimChar), trimChar);
	}

	/**
	 * 把路径中出现 "\" ,"\\" ,"//" 都替换成标准linux 文件分割符 "/"
	 * 
	 * @return
	 */
	public static String convertSeparator(String path) {
		if (!isNull(path)) {
			path = path.replace('\\', '/');
			path = path.replaceAll("//", "/");
		}
		return path;
	}

	/**
	 * 是否以HTTP,HTTPS作为协议开头
	 * @param str
	 * @return
	 */
	public static boolean startWithHTTPProtocol(String str) {
		if (StringUtil.isNull(str)) {
			return false;
		}

		return str.startsWith(PROTOCOL_TYPE_HTTP) || str.startsWith(PROTOCOL_TYPE_HTTPS);
	}

	/**
	 * 功能：判断一个字符串是否包含特殊字符
	 * 
	 * @param string
	 *            要判断的字符串
	 * @return true 提供的参数string仅含特殊HTML标签字符
	 */
	public static boolean isConSpeCharacters(String string) {
		if (string.replaceAll("[\u4e00-\u9fa5]*\\d*-*_*\\s*\\w*", "").length() == string.length()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 计算文本的实际长度,半角字符以0.5长度单位计算
	 * @param html
	 * @return
	 */
	private static String calculateLength(String html) {
		float length = 0;
		char[] charArray = HTMLUtils.wipeOffHTMLTag(html).toCharArray();
		for (int k = 0; k < charArray.length; k++) {
			if ((('\uFF61' <= charArray[k]) && (charArray[k] <= '\uFF9F')) || (('\u0020' <= charArray[k]) && (charArray[k] <= '\u007E'))) {
				length += 0.5;// 半角字符大概占用全角字符的0.5
			} else {
				length += 1;
			}
		}
		return String.valueOf(length);
	}
	
	/**
	 * 计算文本的实际长度,半角字符以0.5长度单位计算
	 * @param html
	 * @return
	 */
	public static int calculateStringLength(String str){
		//计算发送文字的长度
		int msgLength = 0;
		String length = calculateLength(str);
		if(length.endsWith("5")){
			msgLength = (int)Float.parseFloat(length) + 1;
		}else{
			msgLength = (int)Float.parseFloat(length);
		}
		return msgLength;
				
	}
	
}
